const redis = require('./redis.js')
export default {
	data() {
		return {
			imgUrls: [], // banner图
			isFirstLoad: true, // 是否第一次加载
			goodsList: [], // 商品列表
			contentList: [{
				typeName: '全部',
				type: '',
				list: []
			}], // 商品列表(新)
			classyIndex: 0, // 分类索引
			pages: 1, // 当前页码
			pageSize: 1000, // 每页条目数量
			noMore: false, // ，没有更多数据了
			version: "", // app引擎版本号.支付宝要求版本号:10.0.18  微信要求版本号:2.6.0
			newDomain: '',
			ShowOpen: false,
			storeId: '',
			user: {},
			CouponList: [],
			content: "获得优惠券",
			title: "恭喜你",
			couponDiscounts: '',
			// 优惠券
			couponData: {
				useList: [],
				stopList: []
			},
			CouponIdList: "",
			CouponStr: '',
			CouponNum: 0,
			theme: 1,
			domain: "",
			tip: "",
			kefuPhone: '',
			open: '',
		}
	},
	mounted() {
		this.domain = this.$api.Domain
		if (this.domain == "https://shht.wteam.club/app") {
			this.tip = "欢迎使用莱购小程序"
		} else if (this.domain == "https://admin3.51sioc.com/api") {
			this.tip = "欢迎使用云值守小程序"
		} else if (this.domain == "https://shht.wteam.club/api") {
			this.tip = "欢迎使用云值守小程序"
		} else if (this.domain == "https://cw.tmmbuy.com/api") {
			this.tip = "欢迎使用喵喵云便利小程序"
		} else if (this.domain == "https://userbg.czsgaf.com/api") {
			this.tip = "欢迎使用三根云便利小程序"
		}

		this.$forceUpdate()

		let storeId = this.$store.state.storeId
		this.ShowOpen = false

		if (storeId == '' || storeId == null || storeId == undefined) { // 不是通过扫码登录
			this.ShowOpen = false
		} else {
			this.storeId = storeId
			this.ShowOpen = true
			// this.openDoor()

		}

	},

	onLoad(options) {

		if (options.type == 'login') {
			this.CheckToThereCoupon("AfterLogin")
		}
		try {
			const params = options.q.split("%3D");
			const param = params[2]
			console.log('1121', options)
			console.log(22, params)
			console.log(33, param)

			this.$store.state.storeId = param
			this.storeId = param
			uni.setStorageSync("storeId", param) // 就注册会员时候会用到

			this.openDoor()
		} catch (e) {
			//TODO handle the exception
		}

	},
	onShow() {
		this.open = redis.get('open')
		if (wx.getStorageSync("user")) {
			this.user = JSON.parse(wx.getStorageSync("user"))

			if (this.user.isVip == 1)
				this.CheckToThereCoupon("intoMiniProgram")

		}


		// let curRoute  = this.$mp.page.route; // 直接获取当前页面路由
		// console.log(curRoute)

		this.storeId = this.$store.state.storeId
		// if (this.isFirstLoad == false) {
		// 	if (this.$store.state.userInfo.userId) {
		// 		this.whichRole();
		// 	} else {
		// 		uni.showToast({
		// 			title: '未登录',
		// 			icon: "none"
		// 		});
		// 	}
		// }
	},

	/*监听底部上拉事件*/
	onReachBottom() {
		// 由于项目需求，现在暂不使用分页
		// if (this.noMore == false) {
		// 	this.pages++;
		// 	this.getPageData();
		// }
	},
	methods: {
		openTheDoor() {
			let data = {
				storeId: uni.getStorageSync("storeId")
			}


			this.$request(this.$api.applyOpenDoor, data, "POST",
					false).then(res => {
					if (res.code == 200) {
						uni.showModal({
							content: ` 联系客服:+${res.data.phone}`
						})
						// this.kefuPhone=res.data.phone
					} else {}
				})
				.catch(res => {
					uni.hideLoading();
				})

		},
		getToken() {
			let token = wx.getStorageSync("token")

			// this.$refs.popup.open('center')
			if (token == '' || token == null || token == undefined) {
				//不存在则跳转至登录页
				uni.navigateTo({
					url: "/pages/login/login?type=index"
				})
				return;
			} else {
				this.verifyExpired()
			}
		},
		handleGetClick(event) {
			this.LinQuCoupon()
			this.$refs.coupon_pop.show = false
		},
		CheckToThereCoupon(status) {
			let data = {
				storeId: uni.getStorageSync("storeId"),
				status: status
			}
			this.$request(this.$api.CheckToThereCoupon, data, "POST",
					false).then(res => {
					if (res.code == 200) {
						if (res.data.length != 0) {
							let CouponIdList1 = []
							res.data.forEach(item => {

								if (item.type != "offerCoinCoupons") {
									let ruleFieldL = item.yzsActivityRuleList[0].ruleField.split(":")
									item.price = ruleFieldL[1]
									if (ruleFieldL[0] != 0)
										item.minPrice = ruleFieldL[0]
								} else {
									item.goodsName = item.yzsActivityRuleList[0].operationType
									item.num = item.yzsActivityRuleList[0].ruleField
								}
								item.name = item.activityName
								item.endData = item.yzsActivityRuleList[0].presentId
								item.operationType = item.yzsActivityRuleList[0].operationType
								CouponIdList1.push(item.activityId)
							})
							this.CouponList = res.data
							this.$refs.coupon_pop.show = true
							this.CouponIdList = CouponIdList1.join(",")

						}


					} else {
						uni.showToast({
							title: res.description,
							icon: 'error'
						});
					}
				})
				.catch(res => {
					uni.hideLoading();
				})
		},


		LinQuCoupon() {
			let url = this.$api.LinQuCoupon + "?idList=" + this.CouponIdList
			this.$request(url, null, "GET",
					false).then(res => {
					if (res.code == 200) {

						this.CouponUserList(1)
					} else {
						uni.showToast({
							title: res.description,
							icon: 'error'
						});
					}
				})
				.catch(res => {
					uni.hideLoading();
				})

		},
		showModal() {
			if (this.user.isVip == 0) {
				uni.showLoading({
					title: '加载中'
				});
				let storeId = uni.getStorageSync("storeId") // 就注册会员时候会用到
				let url = this.$api.BecameVip + '?storeId=' + storeId
				this.$request(url, null, "GET",
						false).then(res => {
						if (res.code == 200) {
							uni.hideLoading();
							this.$refs.popup.close()
							uni.showToast({
								title: "已成为会员！",
								icon: 'success'
							});
							this.user.isVip = 1
							uni.setStorageSync("user", JSON.stringify(this.user))
						} else {
							uni.hideLoading();
							uni.showToast({
								title: res.description,
								icon: 'error'
							});
						}
					})
					.catch(res => {
						uni.hideLoading();
					})
			} else {
				uni.showToast({
					title: "您已经是会员！",
					icon: 'success'
				});
			}
		},
		close() {
			this.$refs.popup.close()

		},
		OpenDoor() { // 一键开门
			// this.getToken()
			let token = wx.getStorageSync("token")
			if (token == '' || token == null || token == undefined) {
				return;
			}
			let a = {
				"storeId": this.storeId
			}
			uni.showLoading({
				title: '加载中'
			});
			this.$request(this.$api.openDoor, a, "POST",
					false).then(res => { //完善微信用户的电话号码
					console.log('结果', res)
					if (res.code == 200) {
						uni.hideLoading();
						uni.showToast({
							title: "开门成功！",
							icon: 'success'
						});
						this.ShowOpen = false
						this.$store.state.storeId = ''
						this.storeId = ''

						redis.put('open', 1, 8888)
						this.open = 1;

						if (this.user.isVip == 0)
							this.$refs.popup.open('center')
						else {
							this.CheckToThereCoupon("AfterLogin")
						}



					} else {
						uni.hideLoading();
						if (res.descriptio)
							uni.showToast({
								title: res.description,
								icon: 'error'
							});
						else
							uni.showToast({
								title: "开门失败",
								icon: 'error'
							});
					}
				})
				.catch(res => {
					uni.hideLoading();
				})
		},
		// 开启订阅消息
		openMsg() {
			var that = this
			// 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
			wx.getSetting({
				withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
				success(res) {
					console.log(res)
					if (res.authSetting['scope.subscribeMessage']) { //用户点击了“总是保持以上，不再询问”
						uni.openSetting({ // 打开设置页
							success(res) {
								console.log(res.authSetting)
							}
						});
					} else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
						var templateid = [
							'85Rvs1MjxBc8lmjrW4JlAcpJIhwFU0Y9Ku8exN1iygI',
							'zQzXhcPoFbC6nABcgvzv6hVydWyAseuqjPfnI7A2onE',
							'amRxJNM_wUd2uBpkz2txWWkk-jBPN3QQF6YwAd89ixE'
						]
						uni.requestSubscribeMessage({
							tmplIds: templateid,
							success(res) {

							},
							fail: (res) => {
								console.log(res)
								// 他们小程序，就跳转到他们充值小程序

							}
						})
					}
				}
			})
		},


		verifyExpired() {
			this.$request(this.$api.verifyExpired, null, "GET",
				false).then(res => { //完善微信用户的电话号码
				console.log('TOKEN', res)
				if (res.data == false) {
					uni.clearStorageSync()
					uni.navigateTo({
						url: "/pages/login/login"
					})
				} else {

				}
			})
		},
		SaoMaOpenDoor() {

			this.getToken()
			// this.$refs.popup.open('center')
			let token = wx.getStorageSync("token")
			if (token == '' || token == null || token == undefined) {
				return;
			}
			uni.scanCode({
				onlyFromCamera: false,
				success: (res) => {
					// this.storeId = res.result.storeId

					const params = res.result.split("?");
					const param = params[1].split("&");
					const storeId = param[1].split("=")[1];

					console.log('1121', params)
					console.log(22, param)
					console.log(33, storeId)

					this.$store.state.storeId = storeId
					this.storeId = storeId
					uni.setStorageSync("storeId", storeId) // 就注册会员时候会用到

					this.OpenDoor()

					// uni.setStorageSync("storeId", this.storeId)
					console.log('扫码', res)
				},
				complete: (res) => {
					uni.hideLoading();
					// uni.showToast({
					// 	title: '扫码失败',
					// 	icon: 'error'
					// });
				}
			});
			if (this.$api.Domain == "https://shht.wteam.club/api") {
				this.openMsg1()
			} else {
				this.openMsg()
			}
		},


		openMsg1() {
			var that = this
			// 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
			wx.getSetting({
				withSubscriptions: true, //是否获取用户订阅消息的订阅状态，默认false不返回
				success(res) {
					console.log(res)
					if (res.authSetting['scope.subscribeMessage']) { //用户点击了“总是保持以上，不再询问”
						uni.openSetting({ // 打开设置页
							success(res) {
								console.log(res.authSetting)
							}
						});
					} else { // 用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息
						var templateid = [
							'0oc4HEPsewJB-seRWZkQSqrOp53pPXZ-oI7DdyVFDEM',
							'M9lcU-OUzpH_97tsPSDzORV0f-iDE7VEmhC81r7qBDI'
						]
						uni.requestSubscribeMessage({
							tmplIds: templateid,
							success(res) {

							},
							fail: (res) => {
								console.log(res)
								// 他们小程序，就跳转到他们充值小程序

							}
						})
					}
				}
			})
		},

	}
}